#!/usr/bin/env bash
#
# vim:et:ft=sh:sts=2:sw=2
#
#/**
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements.  See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership.  The ASF licenses this file
# * to you under the Apache License, Version 2.0 (the
# * "License"); you may not use this file except in compliance
# * with the License.  You may obtain a copy of the License at
# *
# *     http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# */

# name of script
BK_ARGV0=`basename "$0"`

# path to shUnit2 library. can be overridden by setting BK_SHUNIT_INC.
BK_SHUNIT=${BK_SHUNIT_INC:-../../../target/lib/shunit2-2.1.7/shunit2}

# path to bk bin directory.
TESTDIR=`dirname "$0"`
BK_BINDIR=`cd ${TESTDIR}/../../../../../bin;pwd`
BK_HOMEDIR=`cd ${TESTDIR}/../../../../..;pwd`
BK_CONFDIR=`cd ${TESTDIR}/../../../../../conf;pwd`

#
# test helper functions
#

# message functions
bk_trace() { echo "bk_test:TRACE $@" >&2; }
bk_debug() { echo "bk_test:DEBUG $@" >&2; }
bk_info() { echo "bk_test:INFO $@" >&2; }
bk_warn() { echo "bk_test:WARN $@" >&2; }
bk_error() { echo "bk_test:ERROR $@" >&2; }
bk_fatal() { echo "bk_test:FATAL $@" >&2; }

bk_oneTimeSetUp() {
  # these will be cleaned up automatically by shunit2
  BK_TMPDIR=${SHUNIT_TMPDIR}
  stdoutF="${BK_TMPDIR}/stdout"
  stderrF="${BK_TMPDIR}/stderr"
  expectedF="${BK_TMPDIR}/expected"
}

# Assert the success of an operation.
#
# If an operation is not successful (i.e. it returns a non-zero return code)
# dump the output of the stderrF to the screen.
#
# Args:
#   message: string: message to output [optional]
#   result: integer: operation result
assertSuccess() {
  if [ $# -eq 2 ]; then
    bk_message_=$1
    shift
  else
    bk_message_=''
  fi
  bk_result_=$1

  assertEquals "${bk_message_}" ${SHUNIT_TRUE} ${bk_result_}
  [ ${bk_result_} -eq ${SHUNIT_TRUE} ] || cat "${stderrF}"

  unset bk_message_ bk_result_
}

assertError() {
  if [ $# -eq 2 ]; then
    bk_message_="$1: "
    shift
  else
    bk_message_=''
  fi
  bk_error_=$1

  bk_file_=${stderrF}
  grep "^bk_test:ERROR.*${bk_error_}" "${bk_file_}" >/dev/null
  bk_result_=$?
  assertTrue "${bk_message_}missing '${bk_error_}' error" ${bk_result_}
  [ ${bk_result_} -eq 0 ] || cat "${bk_file_}"

  unset bk_file_ bk_error_ bk_message_ bk_result_
}
